package cn.superlu.s3uploadservice.controller;

import cn.superlu.s3uploadservice.common.R;
import cn.superlu.s3uploadservice.model.bo.FileUploadInfo;
import cn.superlu.s3uploadservice.common.FileTemplate;
import cn.superlu.s3uploadservice.model.entity.SysFileUpload;
import cn.superlu.s3uploadservice.model.vo.BaseFileVo;
import cn.superlu.s3uploadservice.model.vo.UploadUrlsVO;
import cn.superlu.s3uploadservice.service.SysFileUploadService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/files")
@RequiredArgsConstructor
public class SysFileUploadController {

    private final SysFileUploadService fileUploadService;

    /**
     * 检查文件是否存在
     */
    @GetMapping("/multipart/check/{md5}")
    public R<BaseFileVo<FileUploadInfo>> checkFileByMd5(@PathVariable String md5) {
        log.info("查询 <{}> 文件是否存在、是否进行断点续传", md5);
        return fileUploadService.checkFileByMd5(md5);
    }

    /**
     * 初始化文件分片地址及相关数据
     */
    @PostMapping("/multipart/init")
    public R<BaseFileVo<UploadUrlsVO>> initMultiPartUpload(@RequestBody FileUploadInfo fileUploadInfo) {
        log.info("通过 <{}> 初始化上传任务", fileUploadInfo);
        return fileUploadService.initMultipartUpload(fileUploadInfo);
    }

    /**
     * 文件合并（单文件不会合并，仅信息入库）
     */
    @PostMapping("/multipart/merge/{md5}")
    public R<BaseFileVo<String>> mergeMultipartUpload(@PathVariable String md5) {
        log.info("通过 <{}> 合并上传任务", md5);
        return fileUploadService.mergeMultipartUpload(md5);
    }

    /**
     * 下载文件（分片）
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> downloadMultipartFile(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("通过 <{}> 开始分片下载", id);
        return fileUploadService.downloadMultipartFile(id, request, response);
    }

    @GetMapping("/list")
    public R<List<SysFileUpload>> getFileList() {
        return fileUploadService.getFileList();
    }
}
